<template>
  <div class="mousemove-validate" @mouseup="onmouseup" @mousemove="onmousemove">
    <div ref="box" class="box" :class="{ on: isEnd }">
      <p class="tips">{{ tips }}</p>
      <p
        ref="item"
        class="item"
        :style="{ left: moveX + 'px' }"
        @mousedown="onmousedown"
      >
        <i v-if="!isEnd" class="icon el-icon-d-arrow-right" />
        <i v-else class="icon el-icon-check" />
      </p>
    </div>
  </div>
</template>
<script>
export default {
  name: 'MousemoveValidate',
  data() {
    return {
      tips: '请按住滑块，拖到最右边',
      isEnd: false,
      flag: false,
      boxWidth: 0,
      itemWidth: 0,
      startX: 0,
      moveX: 0
    };
  },
  watch: {
    moveX(val) {
      this.moveX = val < 0 ? 0 : val > (this.boxWidth - this.itemWidth) ? (this.boxWidth - this.itemWidth) : val;
    }
  },
  mounted() {
    this.boxWidth = this.$refs.box.offsetWidth;
    this.itemWidth = this.$refs.item.offsetWidth;
  },
  methods: {
    onmousedown(e) {
      this.flag = true;
      this.startX = e.clientX;
    },
    onmousemove(e) {
      this.moveX = this.flag ? (e.clientX - this.startX - 1) : 0;
      if ((this.moveX + this.itemWidth) >= this.boxWidth) {
        this.isEnd = true;
        this.tips = '验证成功';
        this.onmousemove = () => {};
        this.onmousedown = () => {};
      }
      this.$emit('handle', this.isEnd);
    },
    onmouseup() {
      if ((this.moveX + this.itemWidth) < this.boxWidth) {
        this.moveX = 0;
        this.flag = false;
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.mousemove-validate {
  width: 100%;
  position: relative;
  p {
    margin: 0;
    padding: 0;
  }
}
.box {
  height: 40px;
  line-height: 40px;
  border-radius: 20px;
  background-color: #f1f5f9;
  position: relative;
  &.on {
		.tips{
			color: #f75757;
		}
    .item {
      .icon {
        color: #f75757;
      }
    }
  }
}
.tips {
  height: 100%;
  width: 100%;
  font-size: 14px;
  color: #838a9d;
  text-align: center;
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}
.item {
  height: 40px;
  width: 40px;
  box-sizing: border-box;
  border-radius: 50%;
  text-align: center;
  background-color: #fff;
  border: 1px solid #dce1ee;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 2;
  cursor: pointer;
  .icon {
    font-size: 14px;
    color: #dce1ee;
  }
}
</style>
